import 'isomorphic-fetch'

//API middleware
export default store => next => action => {
	console.log('api middleware action:',action);

	const opt = action['API'];
	if (typeof opt === 'undefined') {
	   return next(action)
	}

    let tmps = [],callback = ()=>{},data = opt.data;
    for (let key in data) {
        tmps.push(key + '=' + data[key]);
    }

    let fetchOptions = {
        method: 'POST',
        headers: {
            //'Accept': 'application/json',
            //'Content-Type': 'application/json'
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: tmps.join('&')
    };

    fetchOptions = opt.fetchOptions || fetchOptions;
    callback = opt.callback || callback;

    console.log('fetchRequest:',opt,fetchOptions,callback);

    fetch(opt.url, fetchOptions)
    .then((response) => {
        console.log('fetchResponse:',response);
        return response.json()
    })
    .then((responseData) => {
        callback(next,responseData);
    })
    .catch((error) => {
        console.log(error);
    })

}